<template>
  <el-dialog
    v-bind="$attrs"
    width="1000px"
    :title="dialogForm.id ? '修改个人权限' : '新增个人权限'"
    center
  >
    <el-form
      ref="dialogFormRef"
      :model="dialogForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="选择应用名称" prop="applicationId">
        <el-select
          v-model="dialogForm.applicationId"
          placeholder="请选择应用名称"
          clearable
          filterable
          @change="changeApplication"
        >
          <el-option
            v-for="item in applicationList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择角色" prop="identityCode">
        <el-select
          v-model="dialogForm.identityCode"
          placeholder="选择角色"
          clearable
          filterable
        >
          <el-option
            v-for="item in appNameOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择组织" prop="orgId">
        <el-select
          v-model="dialogForm.orgId"
          placeholder="选择组织"
          clearable
          filterable
          @change="changeuserNames"
        >
          <el-option
            v-for="item in orgList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="选择用户" prop="authValue">
        <el-select
          v-model="dialogForm.authValue"
          placeholder="选择用户"
          clearable
          filterable
        >
          <el-option
            v-for="item in userList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="onclose()">取消</el-button>
        <el-button type="primary" @click="submit(false)" v-if="isDetail"
          >修改</el-button
        >
        <el-button type="primary" @click="submit(true)" v-if="!isDetail">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, onMounted } from "vue";
import Editor from "@/components/Editor/index.vue";
import axios from "axios";
import { apiUrl } from "@/api/api";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: { Editor },
  props: {
    dataForm: Object,
    isDetail: {
      type: Boolean,
      default: false,
    },
    isFabu: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, { emit }) {
    const dialogFormRef = ref();
    const dataMap = reactive({
      dialogForm: {
        id: "",
      },
      appNameOptions: [],
      applicationList: [],
      orgList: [],
      userList: [],
      rules: {
        authValue: [{ required: true, message: "请选择用户", trigger: "blur" }],
        identityCode: [
          { required: true, message: "请选择角色", trigger: "change" },
        ],
        applicationId: [
          { required: true, message: "请选择应用", trigger: "change" },
        ],
        orgId: [{ required: true, message: "请选择组织", trigger: "change" }],
      },
    });

    const fetchAppNames = (value) => {
      let data = {
        pageNum: dataMap.pageIndex,
        pageSize: dataMap.pageSize,
        groups: [],
        rules: [
          {
            field: "applicationId",
            data: value,
            opType: "Equals",
          },
        ],
        orderBys: [],
      };
      axios({
        method: "post",
        url: apiUrl.baseUrl + "/wl/auth/identity/getList",
        data: data,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.appNameOptions = response.data.data.data.map((item) => ({
            value: item.code,
            label: item.name,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const userNames = (value) => {
      let data = {
        pageNum: dataMap.pageIndex,
        pageSize: dataMap.pageSize,
        groups: [],
        rules: [
          {
            field: "orgId",
            data: value,
            opType: "Equals",
          },
        ],
        orderBys: [],
      };
      axios({
        method: "post",
        url: apiUrl.baseUrl + "/wl/auth/orgUser/getList",
        data: data,
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.userList = response.data.data.data.map((item) => ({
            value: item.id,
            label: item.userName,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };
    const orgFun = () => {
      axios({
        method: "post",
        url: apiUrl.baseUrl + "/wl/auth/org/getList",
        data: {},
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.orgList = response.data.data.data.map((item) => ({
            value: item.id,
            label: item.orgName,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };

    const applicationFun = () => {
      axios({
        method: "post",
        url: apiUrl.baseUrl + "/wl/auth/application/getList",
        data: {},
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          loginToken: sessionStorage.getItem("loginToken"),
        },
      })
        .then((response) => {
          dataMap.applicationList = response.data.data.data.map((item) => ({
            value: item.id,
            label: item.applicationName,
          }));
        })
        .catch((error) => {
          console.log(error);
        });
    };

    const changeApplication = (value) => {
      fetchAppNames(value);
    };
    const changeuserNames = (value) => {
      userNames(value);
    };
    const methodsMap = reactive({
      onclose() {
        emit("close");
      },
      submit(flag) {
        if (flag) {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data = dataMap.dialogForm;
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/authentication/create",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  if (response.data.data.code === "-1") {
                    ElMessage.error(response.data.data.message);
                  } else {
                    setTimeout(() => {
                      emit("getDatas");
                      emit("close");
                    }, 500);
                  }
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        } else {
          dialogFormRef.value.validate((valid) => {
            if (valid) {
              let data = {};
              data = dataMap.dialogForm;
              let params = {};
              params.data = data;
              params.rid = "";
              axios({
                method: "post",
                url: apiUrl.baseUrl + "/wl/authentication/save",
                data: params,
                headers: {
                  "Content-Type": "application/json;charset=UTF-8",
                  loginToken: sessionStorage.getItem("loginToken"),
                },
              })
                .then((response) => {
                  setTimeout(() => {
                    emit("getDatas");
                    emit("close");
                  }, 500);
                })
                .catch((error) => {});
            } else {
              return;
            }
          });
        }
      },
    });

    onMounted(() => {
      applicationFun();
      orgFun();
      if (props.dataForm) {
        let temp = JSON.parse(JSON.stringify(props.dataForm));
        dataMap.dialogForm = {
          ...temp,
          authType: "PHONE",
        };
        if (dataMap.dialogForm.applicationId) {
          fetchAppNames(dataMap.dialogForm.applicationId);
        }
        if (dataMap.dialogForm.orgId) {
          changeuserNames(dataMap.dialogForm.orgId);
        }
      }
    });

    return {
      ...toRefs(dataMap),
      ...toRefs(methodsMap),
      dialogFormRef,
      changeApplication, // 将changeApplication暴露给模板
      changeuserNames,
    };
  },
});
</script>
